package com.example.rabbitmq_study.util;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import jdk.internal.org.objectweb.asm.Handle;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @author Huangyt
 * @version 1.0
 * @date 2020/7/28 16:21
 */
@Component
public class RabbitmqUtil {

    private static ConnectionFactory cf;

    //类加载执行，只执行一次
    static {
        //创建连接MQ的连接工厂
        cf = new ConnectionFactory();
        //设置连接MQ服务的主机IP
        cf.setHost("192.168.93.138");
        //设置端口
        cf.setPort(5672);
        //设置连接指定的虚拟主机
        cf.setVirtualHost("/ems");
        //设置访问虚拟主机的用户名和密码
        cf.setUsername("ems");
        cf.setPassword("123");
    }

    //获取mq连接
    public static Connection getConnection() throws IOException, TimeoutException {
        try {
            //获取连接对象
            return cf.newConnection();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    //关闭通道和关闭连接
    public static void close(Channel channel, Connection connection) {
        try {
            channel.close();
            connection.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
    }
}
